/*
 * Classe adaptada de http://www.vogella.com/articles/Logging/article.html
 * 
 */
package x2rel.qMap.logger;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;


public class Logging {
    
    private final static Logger LOGGER = Logger.getLogger(Logging.class.getName());

    static private FileHandler fileTxt;
    static private SimpleFormatter formatterTxt;

    static private FileHandler fileHTML;
    static private Formatter formatterHTML;
    private static SimpleDateFormat date_format;
    private static String date;
    private static Logging instance = null;

    public Logging(){
        try {
            Logging.setup(0);
        } catch (IOException e) {
            throw new RuntimeException("Ocorreu um erro ao gerar o arquivo de log.");
        }
    }
    
    public Logging(Integer level){
        try {
          Logging.setup(level);
        } catch (IOException e) {
            //e.printStackTrace();
            throw new RuntimeException("Ocorreu um erro ao gerar o arquivo de log.");
        }
        instance = this;
    }
    
    public static Logging getInstance(){
        if (instance == null) {
            instance = new Logging();
        }
        return instance;
    }

    static public void setup(Integer level) throws IOException {
      //  System.out.println(level);
        switch(level){ // Seta o nível das mensagens que serão gravadas no log
            case 0 : LOGGER.setLevel(Level.FINEST); break;
            case 1 : LOGGER.setLevel(Level.INFO); break;
            case 2 : LOGGER.setLevel(Level.WARNING); break;
            case 3 : LOGGER.setLevel(Level.SEVERE); break;            
        }

        date_format = new SimpleDateFormat("yyyyMMddHHmmss");
        date = date_format.format(new Date());
        fileTxt = new FileHandler("logs/Log_"+ date.toString() +".txt");
        fileHTML = new FileHandler("logs/Log_"+ date.toString() +".html");

        // Create txt Formatter
        formatterTxt = new SimpleFormatter();
        fileTxt.setFormatter(formatterTxt);
        LOGGER.addHandler(fileTxt);

        // Create HTML Formatter
        formatterHTML = new LogHtmlFormatter();
        fileHTML.setFormatter(formatterHTML);
        LOGGER.addHandler(fileHTML);

    }


    public void log(String message) {
      this.log(message, 0);
    }

    public void log(String message, Integer level) {
        //System.out.println(level);
        switch(level){
            case 0 : LOGGER.finest(message);  break;
            case 1 : LOGGER.info(message);  break;
            case 2 : LOGGER.warning(message);  break;
            case 3 : LOGGER.severe(message);  break;
        }
        
    }
  

}


